package com.imoblife.brainwavestus.user;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.product.Product;
import com.imoblife.brainwavestus.product.ProductInfo;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.util.DebugUtil;

public class UserLocalLib {
	
	private ArrayList<Product> lib;
	
	public UserLocalLib() {
		
		lib = new ArrayList<Product>();
	}
	
	public void clear() {
		
		if(lib != null) {
			
			lib.clear();
		}
	}
	
	public void addProduct(Product product) {
		
		if(null != lib && !lib.contains(product)) {
			
			lib.add(product);
		}
	}
	
	public Set<String> getLocalCategory() {
		
		Set<String> categories= new HashSet<String>();
		
		for(Product product : lib){
			
			String category = product.getProductInfo().getCategory();
			
			if(!categories.contains(category)) {
				
				categories.add(category);
				
				DebugUtil.debug("User local lib", "user local category: " + category);
			}		
		}
		
		return categories;
	}
	
	public ArrayList<Product> getProductByCategory(String category, Store store) {
		
		ArrayList<Product> products = new ArrayList<Product>();
		
		Set<String> set = getLocalCategory();
		
		boolean isAllCategory = set.contains(category);
		
		for(Product product: lib) {
			
			ProductInfo info = product.getProductInfo();
			
			if(isAllCategory && !info.getCategory().equals(category)) {
				
				continue;
			}
			
			if(info.isProductCollection()){
				
				products.add(product);
			}else {
				
				String parentId = info.getParentId();
				//单个产品直接添加
				if(info.getName().equals(parentId)){
					
					products.add(product);
				}else {
					//属于合集中的某个产品
					Product parent = store.getProductByName(parentId);
					
					products.add(parent);
				}
				
			}
		}
		
		return products;
	}
}
